package com.grgbanking.it.common.json;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.hibernate.exception.ConstraintViolationException;

import com.grgbanking.it.system.entity.Department;
import com.grgbanking.it.system.entity.WXMenu;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

/**
 *  生成Json数据
 * 
 * @author rainbow 
 */
public class JSONHelper {
	/**
	 * 默认截取异常大小
	 */
	private static final int ERROR_MSG_SIZE = 30;
	
	/**
	 * 获取从微信回来的异常信息
	 * getErrorFromWX
	 * 
	 * @param json
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String getErrorFromWX(String json){
		return JSONObject.fromObject(json).get("errmsg").toString();
	}
	
	/**
	 * 转换微信菜单数据
	 * converMenu
	 * 
	 * @param menus
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String converMenu(List<WXMenu> menus){
		MenuData data = new MenuData();
		data.setButton(menus);
		String json = JSONObject.fromObject(data).toString();
		json = json.replace("children", "sub_button");
		return json;
	}
	
	/**
	 * 为EXTJS的表格转换数据
	 * convertToGrid
	 * 
	 * @param total
	 * @param data
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String convertToGrid(Long total,List<?> data){
	    GridData grid = new GridData();
	    grid.setTotalCount(total);
	    grid.setData(data);

	    JSONObject jsonArray = JSONObject.fromObject(grid);
	   
	    return jsonArray.toString();
	}
	/**
	 * 为form表单转换json
	 * convertObjectForForm
	 * 
	 * @param data
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String convertObjectForForm(Object data){
		FormData form = new FormData();
		form.setData(data);
		form.setSuccess(true);

		return JSONObject.fromObject(form,createJsonConfig()).toString();
	}
	
	/**
	 * 将一个实体对象转为JSON
	 * convertObject
	 * 
	 * @param data
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String convertObject(Object object){
		return JSONObject.fromObject(object,createJsonConfig()).toString();
	}
	
	
	
	/**
	 * 将一个集合转换成JSON
	 * converList
	 * 
	 * @param list
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String converList(List<?> list){
		return JSONArray.fromObject(list,createJsonConfig()).toString();
	}
	
	private static JsonConfig createJsonConfig() {
		JsonValueProcessor jsonProcessor = new DateJsonValueProcessor();
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        jsonConfig.registerJsonValueProcessor(Date.class, jsonProcessor);
        jsonConfig.registerJsonValueProcessor(Timestamp.class, jsonProcessor);
		return jsonConfig;
	}
	/**
	 * 转换部门数据
	 * convertDepartment
	 * 
	 * @param list
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public static String convertDepartment(List<Department> list) {
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
			// 重写内部的允许字段通过的方法
			public boolean apply(Object source, String name, Object value) {
				// 排除的字段名字（属性名）
				if (name.equals("deptId") || name.equals("deptName")
						|| name.equals("children") || name.equals("leaf")) {
					return false;
				} else {
					return true;
				}
			}
		});

		return JSONArray.fromObject(list, jsonConfig).toString();
	}
	
	/**
	 * 操作成功返回
	 * 
	 * @param okMsg
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public static String getSuccessMessage(String msg) throws Exception {
		return getResponseMessage(msg, 0);
	}
	/**
	 * 操作失败返回
	 * 
	 * @param okMsg
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public static String getFailedMessage(String msg)  {
		return getResponseMessage(msg, 1);
	}
	
	/**
	 * 异常信息
	 * @param e
	 * @return
	 */
	public static String getExceptionMessage(Exception e){
		return getResponseMessage(getErrorMsg(e), 1);
	}
	
	/**
	 * 获取异常大小
	 * 
	 * @param e
	 *            异常
	 * @param size
	 *            大小
	 * @return 截取后的异常
	 */
	public static String getErrorMsg(Exception e) {
		String errorMsg = "";
		if (e.getCause() instanceof ConstraintViolationException) {
			ConstraintViolationException cve = (ConstraintViolationException) e
					.getCause();
			SQLException s = cve.getSQLException();
			errorMsg = s.getMessage().replace("\n", "");
			errorMsg = errorMsg.substring(s.getMessage().lastIndexOf("-") + 1);
		} else {
			errorMsg = e.getMessage();
		}
		if (errorMsg != null && errorMsg.length() > ERROR_MSG_SIZE) {
			errorMsg = errorMsg.substring(0, ERROR_MSG_SIZE) + "...";
		}
		return errorMsg;
	}
	
	
	/**
	 * 返回
	 * 
	 * @param msg
	 * @param msgType
	 *            0为成功,其它为失败
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private static String getResponseMessage(String msg, int msgType){
		StringBuffer response = new StringBuffer("{success:");
		if (msgType == 0){
			response.append("true,'info':'").append(msg);
		}else{
			response.append("false,'info':'操作失败:").append(msg);
		}
		response.append("'}");
		return response.toString();
	}
}
